import copy
import json
import logging
import os

from tools.pc_env import get_cur_app_data_location

app_name = "NxCom"

workspace_base = get_cur_app_data_location(app_name)

app_def_config_file = os.path.join(workspace_base, "def_config.json")
device_config_path = os.path.join(workspace_base, "DeviceList")  # 设备打开后重新生成的配置存储路径
resource_icon_path = os.path.join(os.getcwd(), 'resource', 'icon')

execute_path = os.getcwd()

app_frameless = True


def load_user_config(config_file: str):
    # new device, use default config
    if not os.path.exists(config_file):
        config_file = app_def_config_file
    logging.debug("open config file:" + config_file)
    with open(config_file, 'r', encoding='utf-8') as f:
        try:
            load_dict = json.load(f)
            # 防止字典类型被破坏
            temp = {'DeviceID': load_dict['DeviceID']}
            logging.debug("load config:" + str(temp))
            return temp
        except Exception as e:
            logging.error(e)
            return None


class GlobalConfig:
    args = {
        "ScanTimeout": 0
    }

    def __init__(self):
        self.check_default_config()

    def check_default_config(self):
        """
        检查默认配置文件是否存在,不存在则根据模板创建,以便用于新设备进来时的默认配置
        """
        if not os.path.isfile(app_def_config_file):
            logging.debug("device config directory is not exist, now create")
            if not os.path.exists(workspace_base):
                os.makedirs(workspace_base)
        with open(app_def_config_file, 'w', encoding='utf-8') as f:
            json_str = json.dumps(self.args, indent=4, ensure_ascii=False)
            logging.debug("save config:" + json_str)
            f.write(json_str)

    def save_user_config(self):
        if not os.path.exists(device_config_path):
            logging.debug("device config directory is not exist, now create")
            os.makedirs(device_config_path)
        with open(app_def_config_file, 'w', encoding='utf-8') as f:
            json_str = json.dumps(self.args, indent=4, ensure_ascii=False)
            logging.debug("save config:" + json_str)
            f.write(json_str)

    @staticmethod
    def get_device_config_file(device_id: str):
        """
        根据设备ID生成文件路径,对外的统一接口
        """
        return os.path.join(device_config_path, str(device_id) + '.json')

    def update_config_from_file(self, device_id=""):
        """
        @brief 从文件中读取配置
        软件启动读取一次;
        选择的串口更改时读取一次
        """
        if device_id != "":
            config = load_user_config(self.get_device_config_file(device_id))
            if config is not None:
                logging.debug("device config file is exist, now update it to user_def_config")
                self.args = copy.deepcopy(config)
                logging.debug("after dict copy for new read:" + str(self.ars))
            else:
                # use default
                logging.debug("device id not found,or file is corrupted, used default config")


app_gl_config = GlobalConfig()
